package com.kk.init;

import com.kk.model.Menu;
import com.kk.model.Role;
import com.kk.model.RoleMenuRel;
import com.kk.model.User;
import com.kk.repository.MenuRepository;
import com.kk.repository.RoleMenuRelRepository;
import com.kk.repository.RoleRepository;
import com.kk.repository.UserRrepository;
import lombok.extern.log4j.Log4j2;
import org.hibernate.annotations.common.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 初始化数据
 * @author: kevin
 * @date: 2018-10-14 20:55
 */
@Component
@Log4j2
public class MyApplicationRunner implements ApplicationRunner {

    @Autowired
    private UserRrepository userRrepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private RoleMenuRelRepository roleMenuRelRepository;
    @Autowired
    private MenuRepository menuRepository;

    @Value("${spring.jpa.hibernate.ddl-auto}")
    private String ddl_auto;
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        log.info("===服务启动后，初始化数据等操作===");
        if (StringHelper.isNotEmpty(ddl_auto) && "create".equals(ddl_auto)) {
            User user1 = new User("admin", "admin", "小倩");
            User user2 = new User("test", "test", "test");
            Role role1 = new Role("超级管理员");
            Role role2 = new Role("普通用户");
            Set<Role> roleSet1 = new HashSet<>();
            Set<Role> roleSet2 = new HashSet<>();
            roleSet1.add(role1);
            roleSet2.add(role2);
            user1.setRoles(roleSet1);
            user2.setRoles(roleSet2);
            userRrepository.saveAll(Arrays.asList(user1, user2));

            Menu menu1 = new Menu("系统管理", 1, "#");
            Menu menu11 = new Menu("用户管理", 2, "/mgr");
            Menu menu12 = new Menu("角色管理", 2, "/role");
            menu11.setParent(menu1);
            menu12.setParent(menu1);
            menu1.setIcon("fa-user");
            menuRepository.saveAll(Arrays.asList(menu1, menu11, menu12));

            RoleMenuRel roleMenuRel1 = new RoleMenuRel(role1, menu1);
            RoleMenuRel roleMenuRel2 = new RoleMenuRel(role1, menu11);
            RoleMenuRel roleMenuRel3 = new RoleMenuRel(role1, menu12);
            RoleMenuRel roleMenuRel4 = new RoleMenuRel(role2, menu1);
            roleMenuRelRepository.saveAll(Arrays.asList(roleMenuRel1, roleMenuRel2, roleMenuRel3, roleMenuRel4));

            log.info("初始化数据完成");
        } else {
            log.info("ddl-auto：" + ddl_auto + "不是create操作，不进行初始化数据");

        }

    }
}
